package sg.edu.nus.comp.cs4218.impl.fileutils;

import java.io.File;

import sg.edu.nus.comp.cs4218.fileutils.IDeleteTool;
import sg.edu.nus.comp.cs4218.impl.ATool;
import sg.edu.nus.comp.cs4218.impl.Shell;

public class DeleteTool extends ATool implements IDeleteTool {

	private String message;	
	
	/**
	 * Constructor
	 * 
	 * @param arguments
	 *            - Arguments the tool is going to be executed with.
	 */
	public DeleteTool(String[] arguments) {
		super(arguments);
		setStatusCode(0);
	}

	/**
	 * Deletes the specified file or folder
	 * 
	 * @param toDelete
	 *            - The file or folder to delete
	 * @return true if and only if the file or directory is successfully
	 *         deleted; false otherwise
	 */
	@Override
	public boolean delete(File toDelete) {
		boolean isDeleted = toDelete.delete();

		if (isDeleted) {
			message = "File/Directory has been deleted";
			return isDeleted;
		} else {
			message = "Unable to delete file/directory";
			setStatusCode(1);
			return isDeleted;
		}
	}

	/**
	 * Deletes a file or directory
	 * 
	 * @param stdin
	 *            - Input on stdin. NOT THE ARGUMENTS! Can be null.
	 * @return Output on stdout
	 */
	@Override
	public String execute(File workingDir, String stdin) {

		if (super.args == null) {
			setStatusCode(1);
			message = "Invalid delete command";
		} 
		
		if (getStatusCode() == 0) {
			if (super.args.length >= 1) {
				if (super.args[0].equals("-") == false) {
					File toDelete = Shell.getFile(workingDir, super.args[0]);

					delete(toDelete);
				}
				else {
					if (stdin != null) {
						File toDelete = Shell.getFile(workingDir, stdin);

						delete(toDelete);
					}
					else {
						setStatusCode(1);
						message = "Invalid delete command";
					}
				}
			} else {
				setStatusCode(1);
				message = "Invalid delete command";
			}
		}

		return message;
	}
}
